package likou;

import java.util.*;

/**
 * @author: Tangxz
 * @email: 1171702529@qq.com
 * @cate: 2021/12/30 09:41
 */
public class _846 {
    public static void main(String[] args) {
        _846 one = new _846();
        one.isNStraightHand(new int[]{8,10,12}, 3);
    }

    public boolean isNStraightHand(int[] hand, int groupSize) {
        if (hand.length % groupSize != 0) return false;
        Map<Integer, Integer> map = new HashMap<>();
        Arrays.sort(hand);
        LinkedList<Integer> list = new LinkedList<>();
        for (int i : hand) {
            map.merge(i, 1, Integer::sum);
            if (list.size() == 0 || i != list.getLast()) {
                list.add(i);
            }
        }
        int n = hand.length;
        int next = list.getFirst();
        int i = next;
        for (; ; ) {
            int p = 0;
            for (; p < groupSize && i < next + groupSize; i++) {
                if (map.containsKey(i)) {
                    p++;
                    map.merge(i, -1, Integer::sum);
                    if (map.get(i) == 0) {
                        map.remove(i);
                        list.removeFirst();
                        if (list.size() == 0) {
                            return p==groupSize;
                        }
                        next = list.getFirst();
                    } else if (map.get(i) < 0) return false;
                } else {
                    return false;
                }
            }
            if (p != groupSize) return false;
            i = next;
        }
    }
}
